package ink.teamwork.battery.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ink.teamwork.battery.model.WechatResponse;
import ink.teamwork.battery.util.JSONUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class WechatService {

    private final RedisService redisService;

    @Value("${config.wechatAppId}")
    private String wechatAppId;

    @Value("${config.wechatSecret}")
    private String wechatSecret;

    public WechatResponse login(String code) {
        final String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String newUrl = String.format(loginUrl, wechatAppId, wechatSecret, code);
        return JSON.parseObject(HttpUtil.get(newUrl), WechatResponse.class);
    }

    public WechatResponse getPhoneNumber(String code) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s";
        JSONObject body = new JSONObject();
        body.put("code", code);
        return JSON.parseObject(HttpUtil.post(String.format(url, getAccessToken()), body.toJSONString()), WechatResponse.class);
    }

    private String getAccessToken() {
        String key = "wechat:access_token";
        String accessToken = redisService.get(key);
        if (StringUtils.isBlank(accessToken)) {
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
            url = String.format(url, wechatAppId, wechatSecret);
            WechatResponse response = JSON.parseObject(HttpUtil.get(url), WechatResponse.class);
            redisService.set(key, response.getAccessToken(), response.getExpiresIn() - 200);
            return response.getAccessToken();
        }
        return accessToken;
    }

    @SneakyThrows
    public WechatResponse getAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
        url = String.format(url, wechatAppId, wechatSecret, code);
        String result = HttpUtil.get(url);
        WechatResponse response = JSON.parseObject(result, WechatResponse.class);
        if (StringUtils.isBlank(response.getAccessToken())) {
            log.error("微信认证异常:{}", result);
            throw new RuntimeException("微信认证异常");
        }
        return response;
    }

    public WechatResponse getUserInfo(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
        url = String.format(url, accessToken, openId);
        return JSON.parseObject(HttpUtil.get(url), WechatResponse.class);
    }
}
